/*
 * sampleOC.c
 *
 *  Created on: Jun 11, 2012
 *      Author: ubuntu
 */
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>

int main(int argc, char **argv) {

	if (argc != 2) {
		fprintf(stderr, "Usage %s <substring>\n", argv[0]);
		exit(EXIT_FAILURE);
	}



	char * subString = argv[1];

	int size = 100;
	// ler 100c de cada vez
	char * buffer = NULL;
	int total_bytesRead = 0;
	int n_bytesRead = 0;

	do {

		buffer = (char *) realloc(buffer,
				sizeof(char) * (size + total_bytesRead));
		n_bytesRead = read(STDIN_FILENO, buffer + total_bytesRead, size);

		total_bytesRead += n_bytesRead;

	} while (n_bytesRead > 0);

	if (n_bytesRead == -1) {
		perror("read");
		exit(EXIT_FAILURE);
	}

	//close(STDIN_FILENO);

	// colocar o file terminator
	buffer[total_bytesRead] = '\0';

	// Compute the result
	int nMatches = 0;
	char * positionBeginning = buffer;
	int subStringSize = strlen(subString);
	do {
		positionBeginning = strstr(positionBeginning, subString);
		if (positionBeginning != NULL) {
			nMatches++;

			positionBeginning += subStringSize;
		}
	} while (positionBeginning != NULL);

	fprintf(stdout, "%d\n", nMatches);
//	close(STDOUT_FILENO);

	return 0;
}

